<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/9/24
 * Time: 下午2:13
 */
class Users extends Eloquent
{
    protected $table = "users";

    public static function getUser($phone){
        return Users::where('phone',$phone)
            ->first();
    }

    public static function getUserByToken($token){
        $user_token = UserTokens::where('token',$token)->first();
        if(is_null($user_token)){
            return -2; //token不存在
        }else{
            //校验是否超过时限
            if( time() > Common::datetime2Num($user_token->out_time_at) ){
                return -1; //token失效
            }else{
                $user_data = Users::where('id',$user_token->user_id)
                    ->where('status',1)
                    ->first();
                if(is_null($user_data)){
                    return -3; //用户不存在
                }else{
                    return $user_data;
                }
            }
        }
    }
    /*
     * @Author:      kc
     * @DateTime:    2017-08-23 13:53:10
     * @Description: 获取邀请人与被邀请人的关系
     * @Param: $invite_user_id 邀请人id $be_invite_user_id 被邀请人id
     * */
    public static function getUserInviteRelation($invite_user_id,$be_invite_user_id){
        $Invitation_relation =  UserInvitation::where('user_id',$invite_user_id)
            ->where('invite_user_id',$be_invite_user_id)
            ->first();
        return $Invitation_relation;
    }


    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2017-11-22T11:52:09+0800
     * @param    int                    $user_id            用户id
     * @param    array                  $pack_arr           套餐卡使用情况数租 [{"pack_id"=>1,"num"=>1},{"pack_id"=>1,"num"=>1}]
     * @param    String                 $car_no             车牌号
     * @param    String                 $shop_name          门店
     * @param    String                 $use_time           时间
     * @param    String                 $is_wash            是否洗车单 0不是 1 是的
     * @return   [type]                                       [description]
     */
    public static function checkServiceCardPack($order_id,$user_id,$pack_arr,$car_no,$shop_name,$use_time,$is_wash){
        $user=Users::find($user_id);
        $msg="您购买的套餐卡中,车牌号".$car_no.",";
        $use_array=array();
        $curr_array=array();
        foreach ($pack_arr as $_pa) {
            $pd=ProductPackage::find($_pa["pack_id"]);
            $temp=DB::select("SELECT  sum(scdp.curr_number) as number
                FROM
                    service_card_detail scd
                LEFT JOIN service_card_base scb ON scb.id = scd.service_card_base_id
                LEFT JOIN service_card_detail_pack scdp ON scdp.service_card_detail_id = scd.id
                WHERE
                    scd.user_id = ?
                AND scd.`status` = 2
                and scdp.pack_id=?
                AND scb.user_status = 1
                and scd.end_date>=?",array($user->id,$_pa["pack_id"],date("Y-m-d 23:59:59",time())));
            $msg=$msg.$pd->name."服务已核销".$_pa["num"]."次,当前剩余".$temp[0]->number."次。";
            $use_array[]=$pd->name."服务".$_pa["num"]."次";
            $curr_array[]=$pd->name."服务当前剩余".$temp[0]->number."次";
        }
        Sms::send_message("",$user->phone,$msg);
        if(isset($user)&&$user->openid){
            $templateId = Config::get('config.scs_servicecard_end_templateId');
            $url = Config::get('config.redirect_url').'/order/show?is_wash='.$is_wash.'&order_id='.$order_id;
            $data = array(
                "first"  => "车主您好，您的车辆".$car_no."在".$shop_name."，套餐卡消费如下！",
                "keyword1" => implode(",",$use_array),
                "keyword2"   => $use_time,
                "keyword3"   => implode(",",$curr_array),
                "remark" => "感谢您使用安惠车服"
            );
            Log::info($data);
            try {
                WechatOauthController::sendMessage($user->openid, $templateId, $data, $url);
            }catch(Exception $e){
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
            }
        }

    }

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2017-11-27T10:54:29+0800
     * @param    innt                   $user_id            用户id
     * @return   [type]                                       [description]
     */
    public static function checkMember($user_id){
        return DB::transaction(function () use ($user_id) {
            if(in_array($user_id, array(1000000000,1879))){
                return;
            }
            $users=Users::where("id",$user_id)->lockForUpdate()->first();
            $now_member=MemberOrdinary::find($users->member);
            $now_experience=isset($now_member)?$now_member->experience:0;
            if($now_experience<$users->experience){//如果经验大于当前会员的经验 说明 改升级会员
                $mo_array=MemberOrdinary::where("experience",">",$now_experience)->where("experience","<=",$users->experience)->where("user_type",$users->type)->where("status",1)->orderBy("experience","asc")->get();//获取 该升几级会员
                $temp_member=$users->member;
                foreach ($mo_array as $_mo) {//循环发放会员
                    $temp_mo=UserMember::where("user_id",$users->id)->where("member",$_mo->id)->orderBy("created_at","desc")->first();//获取上次获取该级别会员时间
                    if(is_null($temp_mo)||(strtotime($temp_mo->created_at)+$_mo->cycle*3600*24)<time()){                //说名没有获取过该级别的 会员或者上次获得该会员已经超期
                        $moc=MemberOrdinaryCoupons::where("member_id",$_mo->id)->where("status",1)->get();              //获取该级别会员应该发放的优惠券信息
                        foreach ($moc as $_moc) {                                                                       //循环方法 该级别优惠券
                            $tcbi=CouponBaseInfo::find($_moc->coupon_id);
                            $input = array(
                                'coupon_base_info_id'   => $tcbi->id,
                                'status'       => 2,
                                'received_user_id' => $users->id,
                                'used_user_id'      => 0,
                                'created_at' => date('Y-m-d H:i:s',time()),
                                'updated_at' => date('Y-m-d H:i:s',time()),
                                'get_time' => date('Y-m-d H:i:s',time()),
                            );
                            if($tcbi->date_type == 1) { //顺延日期
                                $input['end_date'] = date("Y-m-d", strtotime("+" . $tcbi->date_num . " day"));
                            }
                            $bag = array();
                            for ($i = 0; $i < $_moc->number; $i++){
                                //生成统一的优惠码
                                if($tcbi->code_type == 1){ //1 代表 随机码
                                    $bonus_arr = Helper::getStr($tcbi->id,0);
                                    if($tcbi->type == 1){
                                        $bonus_sn = 'jm'.date("m",time()).date("d",time()).$bonus_arr['str_num'];
                                    }
                                    if($tcbi->type == 2){
                                        $bonus_sn = 'fw'.date("m",time()).date("d",time()).$bonus_arr['str_num'];
                                    }
                                    if($tcbi->type == 3){
                                        $bonus_sn = 'sw'.date("m",time()).date("d",time()).$bonus_arr['str_num'];
                                    }
                                    if($tcbi->type == 4){
                                        $bonus_sn = 'fj'.date("m",time()).date("d",time()).$bonus_arr['str_num'];
                                    }
                                    if($tcbi->type == 5){
                                        $bonus_sn = 'fd'.date("m",time()).date("d",time()).$bonus_arr['str_num'];
                                    }
                                }else{
                                    $bonus_sn = $tcbi->code;
                                }
                                $input['code'] = $bonus_sn;
                                $bag[] = $input;
                            }
                            DB::table('coupons')->insert($bag);
                        }
                    }
                    $um=new UserMember();//记录上次获取该级别的额 会员信息
                    $um->user_id=$users->id;
                    $um->member=$_mo->id;
                    $um->save();
                    $temp_member=$_mo->id;
                }
                $users->member=$temp_member;
                $users->save();
            }elseif($now_experience>$users->experience){//如果经验小于当前会员的经验 说明 改降级会员
                $mo_array=MemberOrdinary::where("experience","<=",$users->experience)->where("user_type",$users->type)->where("status",1)->orderBy("experience","desc")->first();//获取 降到那个会员级别
                $users->member=isset($mo_array)?$mo_array->id:0;
                $users->save();
            }         
        });
    }

    /**
     * 异步将远程链接上的内容(图片或内容)写到本地
     * @param  $url    String  远程地址
     * @param  $saveName  String   保存在服务器上的文件名
     * @param  $path String    保存路径
     * @return boolean
     */
    public static function put_file_from_url_content($url, $saveName, $path) {
        // 设置运行时间为无限制
        set_time_limit ( 0 );
        $url = trim ( $url );
        $curl = curl_init ();
        // 设置你需要抓取的URL
        curl_setopt ( $curl, CURLOPT_URL, $url );
        // 设置header
        curl_setopt ( $curl, CURLOPT_HEADER, 0 );
        // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
        // 运行cURL，请求网页
        $file = curl_exec ( $curl );
        // 关闭URL请求
        curl_close ( $curl );
        // 将文件写入获得的数据
        $filename = $path . $saveName;
        $write = @fopen ( $filename, "w" );
        if ($write == false) {
            return false;
        }
        if (fwrite ( $write, $file ) == false) {
            return false;
        }
        if (fclose ( $write ) == false) {
            return false;
        }
    }


    /**
     * @Author   sqq                      <ahsqq@anhuibj.com>
     * @DateTime 2018-10-18T10:05:29+0800
     * @param    int                   $phone            用户手机号
     * @param    int                   $type            用户类型
     * @return  []
     */
    public static function getTypeUser($phone,$type){
        return Users::where('phone',$phone)
            ->where('type',$type)
            ->first();
    }

}